package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.ProblemMapper;
import com.example.pojo.dto.problem.ProblemQueryRequest;
import com.example.pojo.entity.question.Problem;
import com.example.pojo.vo.problem.ProblemVo;
import com.example.service.ProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProblemServiceImpl extends ServiceImpl<ProblemMapper, Problem> implements ProblemService {

    @Autowired
    private ProblemMapper problemMapper;


    // 查询所有题目列表
    @Override
    public Page<ProblemVo> listAll(ProblemQueryRequest problemQueryRequest) {
        int pageNum = problemQueryRequest.getPageNum();
        int pageSize = problemQueryRequest.getPageSize();
        LambdaQueryWrapper<Problem> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(problemQueryRequest.getDifficulty() != null && !problemQueryRequest.getDifficulty().isEmpty(), Problem::getDifficulty, problemQueryRequest.getDifficulty())
                .and(!CollectionUtils.isEmpty(problemQueryRequest.getTags()), wq -> {
                    for (int i = 0; i < problemQueryRequest.getTags().size(); i++) {
                        wq.like(Problem::getTags, problemQueryRequest.getTags().get(i));
                    }
                });
        Page<Problem> problemPage = problemMapper.selectPage(new Page<>(pageNum, pageSize), lambdaQueryWrapper);
        List<ProblemVo> problemVoList = problemPage.getRecords().stream().map(ProblemVo::objToVo).collect(Collectors.toList());
        Page<ProblemVo> problemVo = new Page<>(pageNum, pageSize, problemPage.getTotal());
        problemVo.setRecords(problemVoList);
        return problemVo;
    }

    // 根据id获取题目详情
    @Override
    public ProblemVo selectById(Long id) {
        Problem problem = problemMapper.selectById(id);
        return ProblemVo.objToVo(problem);
    }
}
